<script setup lang="ts">
import {
  getLibraryList,
  libraryaOptions,
  controlTaskChange,
} from "@/api/task/index";
import type {
  RequestParams,
  //bookReturn,
  LibraryPageVo,
  Params,
} from "@/api/task/types";

import { onBeforeUnmount, onMounted, reactive, ref } from "vue";
import useUserStore from "@/store/modules/user";
import { ElMessage, ElMessageBox } from "element-plus";
//let useStore = useUserStore();
const libraryList = ref([{ id: 1, libraryName: "222" }] as LibraryPageVo[]); //列表数据
const bookLibraryList = ref([{ id: 1, bookName: "333" }] as any[]); //列表数据

//const queryFormRef = ref(); //refForm
const ids = ref([]); //表格全选
const total = ref();

let queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  endTime: "",
  startTime: "",
  taskStatus: null,
} as RequestParams);
// const taskStatusOptions = [
//   { label: "启动失败", value: -1 },
//   { label: "等待", value: 0 },
//   { label: "进行中", value: 1 },
//   { label: "暂停", value: 2 },
//   { label: "完成", value: 3 },
//   { label: "其他", value: 255 },
// ];
const centerDialogVisible = ref(false);
/**
 * 列表数据
 */

const getList = async () => {
  loading.value = true;
  try {
    const res = await getLibraryList(queryParams.value);
    libraryList.value = res.data.records;
    total.value = res.data.total;
    //console.log(res.data.records, "还书任务分页列表");
    loading.value = false;
    //console.log(res, "res");
  } catch (error) {
    loading.value = false;
    console.error(error);
  }
};

const params = ref({ pageNum: 1, pageSize: 10 } as Params);
const details = async (row: any) => {
  params.value.taskId = row.id;
  const res = await libraryaOptions(params.value);
  //console.log(res, "详情");
  bookLibraryList.value = res.data.records!;
  centerDialogVisible.value = true;
  dTotal.value = res.data.total;
};
/**
 * 重置
 */
// const resetQuery = () => {
//   queryParams.value = {} as RequestParams;
//   queryParams.value.pageNum = 1;
//   queryParams.value.pageSize = 10;
//   getList();
// };
/**
 * 行checkbox change事件
 */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}
/**
 * 枚举
 */
const getbooksStatus = (status: number) => {
  const STATUSES = [
    { id: -1, name: "启动失败" },
    { id: 0, name: "等待" },
    { id: 1, name: "进行中" },
    { id: 2, name: "暂停" },
    { id: 3, name: "完成" },
    { id: 255, name: "其他" },
  ];
  const matched = STATUSES.find((item) => item.id === status);

  return matched ? matched.name : "";
};
const getcorrect = (status: number) => {
  const STATUSES = [
    { id: 0, name: "错误" },
    { id: 1, name: "正确" },
  ];
  const matched = STATUSES.find((item) => item.id === status);
  return matched ? matched.name : "";
};
const shouldInventory = (status: number) => {
  const STATUSES = [
    { id: 0, name: "未还" },
    { id: 1, name: "已还" },
  ];
  const matched = STATUSES.find((item) => item.id === status);
  return matched ? matched.name : "";
};
const loading = ref(false);

// 控制序号
const indexMethod = (index: any) => {
  // 1、index:代表当前行数据的下标
  // 2、下标+1:  分页不要纠结：这块不是业务，完全是数学问题！
  return (
    index + 1 + (queryParams.value.pageNum - 1) * queryParams.value.pageSize
  );
};
const setTime = ref();
onMounted(() => {
  getList();
  setTime.value = setInterval(() => {
    getList();
    //console.log(123);
  }, 6000);
});
onBeforeUnmount(() => {
  clearInterval(setTime.value);
});
const handleSizeChange = (val: number) => {
  queryParams.value.pageSize = val;
  queryParams.value.pageNum = 1;

  getList();
};
const handleCurrentChange = (val: number) => {
  queryParams.value.pageNum = val;
  getList();
  window.scrollTo({ top: 0, behavior: "smooth" }); // 立即回到顶部，并使用平滑滚动效果
};
const dTotal = ref();
const SizeChange = async (val: number) => {
  params.value.pageSize = val;
  params.value.pageNum = 1;

  const res = await libraryaOptions(params.value);
  // console.log(res, "详情");
  bookLibraryList.value = res.data.records!;
};
const CurrentChange = async (val: number) => {
  params.value.pageNum = val;
  const res = await libraryaOptions(params.value);
  //  console.log(res, "详情");
  bookLibraryList.value = res.data.records!;
  window.scrollTo({ top: 0, behavior: "smooth" }); // 立即回到顶部，并使用平滑滚动效果
};
// --------------------------------------
const DialogVisible = ref(false);
const FormRef = ref();
const ruleForm = ref({} as any);
const invRouteId = ref([] as any);
const rules = reactive({
  routeId: [{ required: true, message: "请选择盘点路线", trigger: "blur" }],
  libraryId: [{ required: true, message: "请选择图书馆", trigger: "change" }],
});
const libraryaOpt = ref();
// const handleAdd = async () => {
//   DialogVisible.value = true;
//   const { data } = await LibraryOptions(useStore.encryptedData);
//   libraryaOpt.value = data;
//   //console.log(data, "图书馆");
// };
const close = () => {
  DialogVisible.value = false;
  FormRef.value.resetFields();
  ruleForm.value = {} as any;
};
const submit = async () => {
  try {
    // 表示当前页面正在异步处理中
    loading.value = true;
    // 验证表单数据是否合法
    const isValid = await FormRef.value.validate();
    if (isValid) {
      ElMessageBox.confirm("确认开始盘点吗", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          //console.log(ruleForm.value.routeId, "杀杀杀撒海");
          // 提交数据到服务器
          const res = await inventoryTask(ruleForm.value);
          if (res.code === 200) {
            ElMessage.success("创建成功");
            //   // 关闭对话框并重新查询列表数据
            close();

            loading.value = false;
          } else {
            close();
            ElMessage.error(res.msg);
            getList();
            loading.value = false;
          }
        })
        .catch(() => {
          loading.value = false;
          close();
          ElMessage.error(res.msg);
        });
    }
  } catch (error) {
    console.error(error);
    // 在发生异常时，取消页面加载状态
    loading.value = false;
  }
};
const changeLib = async (e: any) => {
  ruleForm.value.routeId = "";
  // -----------------------
  const { data } = await inventoryRouteOptions(e);
  invRouteId.value = data;
  //console.log(data, "路线下拉");
};
// ----------------------
const Start = (row: any) => {
  let numstatus = 1;
  // console.log(row);
  ElMessageBox.confirm("确认开始吗", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    setTimeout(async () => {
      const res = await controlTaskChange(numstatus, row.id);
      if (res.code === 200) {
        ElMessage.success("已开始！");
        //   // 关闭对话框并重新查询列表数据

        getList();
        loading.value = false;
      } else {
        ElMessage.error(res.msg);
        getList();
      }
    }, 1000); // 延迟1秒
  });
};
const Pause = (row: any) => {
  let numstatus = 2;
  // console.log(row);
  ElMessageBox.confirm("确认暂停吗", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    setTimeout(async () => {
      const res = await controlTaskChange(numstatus, row.id);
      if (res.code === 200) {
        ElMessage.success("已暂停！");
        //   // 关闭对话框并重新查询列表数据

        getList();
        loading.value = false;
      } else {
        ElMessage.error(res.msg);
        getList();
      }
    }, 1000); // 延迟1秒
  });
};
const Stop = (row: any) => {
  let numstatus = 3;
  //console.log(row);
  ElMessageBox.confirm("确认停止吗", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    setTimeout(async () => {
      const res = await controlTaskChange(numstatus, row.id);
      if (res.code === 200) {
        ElMessage.success("已停止！");
        //   // 关闭对话框并重新查询列表数据
        getList();
        loading.value = false;
      } else {
        ElMessage.error(res.msg);
        getList();
      }
    }, 1000); // 延迟1秒
  });
};

const scheduleFormatter = (row: any) => {
  // console.log(row.schedule, "row");
  if (row.schedule === 1) {
    return "100%";
  } else if (row.schedule === 0) {
    return "0%";
  } else {
    return `${(row.schedule * 100).toFixed(2)}%`;
  }
};
</script>

<template>
  <div class="app-container">
    <div class="search">
      <!-- <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="开始时间">
          <el-input
            v-model="queryParams.startTime"
            placeholder="请输入开始时间"
          />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-input
            v-model="queryParams.endTime"
            placeholder="请输入结束时间"
          />
        </el-form-item>
        <el-form-item label="任务状态">
          <el-select
            v-model="queryParams.taskStatus"
            placeholder="请选择任务状态"
            style="width: 200px"
          >
            <el-option
              v-for="status in taskStatusOptions"
              :value-key="status.value"
              :label="status.label"
              :value="status.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getList">搜索</el-button>
          <el-button type="info" @click="handleAdd">立即盘点</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form> -->
    </div>
    <el-card>
      <el-table
        highlight-current-row
        :data="libraryList"
        :border="true"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="index"
          width="80"
          label="序号"
          :align="'center'"
          :index="indexMethod"
        />

        <el-table-column
          label="图书馆名称"
          prop="libraryName"
          :align="'center'"
          width="120px"
        />

        <el-table-column
          label="机器人编号"
          prop="taskNo"
          :align="'center'"
          width="200px"
        />

        <el-table-column
          label="图书复位机器人编号"
          prop="agvNo"
          :align="'center'"
          width="200px"
        />
        <el-table-column
          label="还书数量"
          prop="totalCount"
          :align="'center'"
          width="120px"
        />
        <el-table-column
          label="已还数量"
          prop="returnCount"
          :align="'center'"
          width="120px"
        />
        <el-table-column
          label="任务状态"
          prop="taskStatus"
          :align="'center'"
          width="120px"
        >
          <template #default="{ row }">
            {{ getbooksStatus(row.taskStatus) }}
          </template>
        </el-table-column>
        <!-- <el-table-column
          label="当前盘点书架"
          prop="currentShelf"
          :align="'center'"
          width="110"
        /> -->

        <el-table-column
          label="开始时间"
          prop="startTime"
          :align="'center'"
          width="120px"
        />
        <el-table-column
          label="结束时间"
          prop="endTime"
          :align="'center'"
          width="120px"
        />
        <!-- <el-table-column
          label="应盘书架数量"
          prop="shelfShouldCount"
          :align="'center'"
          width="110"
        /> -->
        <!-- <el-table-column
          label="应盘rfid数量"
          prop="rfidShouldCount"
          :align="'center'"
          width="110"
        /> -->
        <!-- <el-table-column
          label="实盘rfid数量"
          prop="rfidRealCount"
          :align="'center'"
        /> -->

        <!-- <el-table-column label="盘点进度" prop="schedule" :align="'center'">
          <template #default="{ row }">
            {{ scheduleFormatter(row) }}
          </template>
        </el-table-column> -->
        <!-- <el-table-column label="执行人" prop="operatorName" :align="'center'" /> -->
        <!-- <el-table-column
          label="结束时间"
          prop="endTime"
          :align="'center'"
          width="110"
        /> -->
        <el-table-column fixed="right" label="操作" :align="'center'">
          <template #default="{ row }">
            <div
              style="
                display: flex;
                align-items: center;
                justify-content: center;
              "
            >
              <el-icon :size="20" v-if="row.taskStatus === 2"
                ><VideoPlay
                  style="font-size: 24px; color: #409eff"
                  class="el-icon-video-play"
                  @click="Start(row)"
              /></el-icon>
              <el-icon :size="20" v-if="row.taskStatus === 1"
                ><VideoPause
                  style="font-size: 24px; color: #409eff"
                  class="el-icon-video-pause"
                  @click="Pause(row)"
              /></el-icon>
              <el-icon
                :size="20"
                v-if="
                  row.taskStatus === 1 ||
                  row.taskStatus === 2 ||
                  row.taskStatus === 0
                "
                ><SwitchButton
                  style="font-size: 24px; color: #409eff"
                  class="el-icon-switch-button"
                  @click="Stop(row)"
              /></el-icon>
              <el-button type="primary" link size="small" @click="details(row)"
                >详情</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 15px"
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 30, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <el-dialog v-model="DialogVisible" title="盘点" width="550px">
      <el-form
        ref="FormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="95px"
      >
        <el-form-item
          label="图书馆"
          prop="libraryId"
          style="white-space: nowrap"
        >
          <el-select
            v-model="ruleForm.libraryId"
            placeholder="请选择图书馆"
            @change="changeLib"
          >
            <el-option
              v-for="item in libraryaOpt"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="盘点路线" prop="routeId">
          <el-select v-model="ruleForm.routeId" placeholder="请选择任务状态">
            <el-option
              v-for="(status, index) in invRouteId"
              :key="index"
              :label="status.label"
              :value="status.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submit">确 定</el-button>
          <el-button @click="close">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 详情 -->
    <el-dialog v-model="centerDialogVisible" title="详情" width="60%"
      ><el-table v-loading="loading" :data="bookLibraryList">
        <el-table-column
          label="图书馆名称"
          prop="libraryName"
          :align="'center'"
        />
        <el-table-column label="RFID编码" prop="rfid" :align="'center'" />
        <el-table-column label="还书时间" prop="popTime" :align="'center'" />
        <el-table-column label="放入时间" prop="pushTime" :align="'center'" />
        <el-table-column label="位置" prop="position" :align="'center'" />
        <el-table-column label="状态" prop="returnStatus" :align="'center'">
          <template #default="{ row }">
            {{ shouldInventory(row.returnStatus) }}
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 15px"
        v-model:current-page="params.pageNum"
        v-model:page-size="params.pageSize"
        :page-sizes="[10, 20, 30, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="dTotal"
        @size-change="SizeChange"
        @current-change="CurrentChange"
      />
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
* {
  list-style: none;
}

el-select {
  padding-bottom: 100px;
}

.el-icon-video-play {
  cursor: pointer;
}

.el-icon-video-pause {
  color: blue($color: #000);
  cursor: pointer;
}

.el-icon-switch-button {
  cursor: pointer;
}
</style>
